package devcken.hibernate.query;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

public class NamedQueryHelper
{
	public static Query buildOrderAndGroup(Session session, String namedQueryName, List<OrderColumn> orderByColumns, List<String> groupByColumns)
	{
		Query namedQuery = session.getNamedQuery(namedQueryName);
		
		String queryString = namedQuery.getQueryString();
		
		StringBuilder stringBuilder = new StringBuilder(queryString);
		
		if (orderByColumns != null)
		{
			int orderByColumnCount = orderByColumns.size();
	
			if (orderByColumnCount > 0)
			{
				stringBuilder.append("\n");
				stringBuilder.append("ORDER BY");
				
				for (int index = 0; index < orderByColumnCount; index++)
				{
					OrderColumn orderColumn = orderByColumns.get(index);
					
					stringBuilder.append("\n\t");
					
					if (index < orderByColumnCount - 1)
					{
						stringBuilder.append(String.format("%s %s,", orderColumn.getColumnName(), orderColumn.getColumnOrderBy().value));
					}
					else
					{
						stringBuilder.append(String.format("%s %s", orderColumn.getColumnName(), orderColumn.getColumnOrderBy().value));
					}
				}
			}
		}
		
		if (groupByColumns != null)
		{
			int groupByColumnCount = groupByColumns.size();
			
			if (groupByColumnCount > 0)
			{
				stringBuilder.append("\n");
				stringBuilder.append("GROUP BY");
				
				for (int index = 0; index < groupByColumnCount; index++)
				{
					String groupColumnName = groupByColumns.get(index);
					
					stringBuilder.append("\n\t");
					
					if (index < groupByColumnCount - 1)
					{
						stringBuilder.append(String.format("%s,", groupColumnName));
					}
					else
					{
						stringBuilder.append(String.format("%s", groupColumnName));
					}
				}
			}
		}
		
		SQLQuery buildQuery = session.createSQLQuery(stringBuilder.toString());
		
		return buildQuery;
	}
}